<template>
    <div>
      <h3 class="title">公告详情</h3>
      <el-divider />
      <el-form :model="detailData">
        <el-form-item label="公告标题">
          <el-input v-model="detailData.title" required placeholder="请输入公告标题" />
        </el-form-item>

        <el-form-item label="公告内容">
          <el-input v-model="detailData.content" required type="textarea" rows="5"
            placeholder="请输入公告内容" />
        </el-form-item>
  
        <el-form-item>
          <el-button @click="submit" class="fullBtn" type="primary">提交</el-button>
          <el-button @click="back" class="fullBtn" type="danger">返回</el-button>
        </el-form-item>
  
      </el-form>
    </div>
  </template>
  
  <script setup>
  import { watch, inject, ref } from "vue"
  import { useRouter } from 'vue-router'
  const router = useRouter()
  const $axios = inject('$axios')
  const $root = inject('$root')
  let detailData = ref({})
  
  /* 获取详情数据 */
  const getDetailData = () => {
    const id = router.currentRoute.value.params.id
    detailData.value = {}
    if (id) {
      $axios.get($root + `/notice/${id}/`).then(r => {
        console.log(r)
        if (r.data.code == 200) {
          detailData.value = r.data.data
        }
      })
    }
  }
  
  /* 提交 */
  const submit = () => {
    const id = router.currentRoute.value.params.id
    if (id) {
      update(id)
    }
    else {
      add()
    }
  }
  /* 更新数据 */
  const update = (id) => {
    $axios.post($root + `/notice/update/${id}/`, detailData.value)
      .then(r => {
        if (r.data.code = 200) {
          ElMessage({
            message: '更新数据成功',
            type: 'success',
          })
        }
        else {
          ElMessage.error('更新数据失败')
        }
      })
  }
  
  /* 添加数据 */
  const add = () => {
    $axios.post($root + `/notice/`, detailData.value)
      .then(r => {
        if (r.data.code = 200) {
          ElMessage({
            message: '添加数据成功',
            type: 'success',
          })
        }
        else {
          ElMessage.error('添加数据失败')
        }
      })
  }
  /* 返回 */
  const back = () => {
    router.back()
  }
  
  watch(() => router.currentRoute.value.name, (name) => {
    if (name == "noticeDetail") {
      getDetailData()
    }
  }, { immediate: true, deep: true })
  
  </script>
  
  <style>
  .el-form-item__content {
    display: flex;
    justify-content: center;
  }
  </style>